package cn.xspace.module.other.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.xspace.android.xafcommon.base.BaseAct;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.ExpUtils;
import com.xspace.android.xafcommon.util.PreferencesUtils;
import com.xspace.android.xafcommon.util.StringUtils;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;

import cn.xspace.library.ui.activity.LoginAct;
import cn.xspace.module.other.http.impl.FetchVertifyCodeImpl;
import cn.xspace.module.other.http.impl.ForgetPasswordImpl;
import cn.xspace.module.other.http.impl.RegisterImpl;
import cn.xspace.module.other.http.intface.IFetchVertifyCode;
import cn.xspace.module.other.http.intface.IForgetPassword;
import cn.xspace.module.other.http.intface.IRegister;
import cn.xspace.module.other.util.RProxy;

public class RegisterAct extends BaseAct {
    private EditText mInputMobileEdtTxt;
    private EditText mPasswordET;
    private EditText mConfirmPasswordET;
    private EditText mVertifyCodeET;
    private final NotEmptyTextWatcher mTextWatcher = new NotEmptyTextWatcher();
    private LinearLayout fetchVerCodeLL;
    private ScrollView registerSclVi;
    private IFetchVertifyCode fetchVertifyCode;
    private IRegister register;
    private IForgetPassword forgetPassword;
    private ProgressDialog progressDialog;
    private boolean isRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(RProxy.registeract);
        initView();

        progressDialog = DialogHelp.getWaitDialog(this, getString(RProxy.registeract_prodlg_waiting_fetch_vertifycode_hint));
        progressDialog.show();

        fetchVertifyCode = new FetchVertifyCodeImpl(this);
        register = new RegisterImpl(this);
        forgetPassword = new ForgetPasswordImpl(this);
    }

    private void initView() {
        setTitleBarBg(findViewById(RProxy.r_item));
        fetchVerCodeLL = (LinearLayout) findViewById(RProxy.registeract_fetch_vercode_ll);
        registerSclVi = (ScrollView) findViewById(RProxy.registeract_register_sclVi);
        mInputMobileEdtTxt = (EditText) findViewById(RProxy.registeract_input_mobile_edtTxt);
        mInputMobileEdtTxt.addTextChangedListener(mTextWatcher);
        mPasswordET = (EditText) findViewById(RProxy.registeract_password_edtTxt);
        mPasswordET.addTextChangedListener(mTextWatcher);
        mConfirmPasswordET = (EditText) findViewById(RProxy.registeract_confirm_password_edtTxt);
        mConfirmPasswordET.addTextChangedListener(mTextWatcher);
        mVertifyCodeET = (EditText) findViewById(RProxy.registeract_vercode_edtTxt);
        mVertifyCodeET.addTextChangedListener(mTextWatcher);

        String arm = getIntent().getStringExtra("arm");
        isRegister = (arm != null) && arm.equals("register");
        if (!isRegister) {
            ((Button) findViewById(RProxy.registeract_register_btn))
                    .setText(RProxy.registeract_register_btn_other_text);
            ((TextView) findViewById(RProxy.registeract_title_txtView))
                    .setText(RProxy.registeract_register_btn_other_text);
        }
    }

    public void register(View view) {
        boolean create = true;
        // 判断密钥长度
        String mobile = mInputMobileEdtTxt.getText().toString().trim();
        String password = mPasswordET.getText().toString().trim();
        String vertifyCode = mVertifyCodeET.getText().toString().trim();
        if (ExpUtils.validateLengthshorter(password, 6)) {
            String errorTip = getString(RProxy.registeract_password_edttxt_passwords_too_short);
            mPasswordET.setError(String.format(errorTip, "6"));
            create = false;
        }
        if (!ExpUtils.validateStringIsEquals(password, mConfirmPasswordET
                .getText().toString().trim())) {
            mConfirmPasswordET
                    .setError(getString(RProxy.registeract_confirm_password_edttxt_passwords_not_equal));
            create = false;
        }
        if (create) {
            if (isRegister) {
                progressDialog
                        .setMessage(getResources().getString(RProxy.registeract_prodlg_waiting_register_hint));
                showDialog();
                registerAccount(mobile, password, vertifyCode);
            } else {
                progressDialog
                        .setMessage(getResources().getString(RProxy.registeract_prodlg_waiting_find_passowrd_hint));
                showDialog();
                resetPwd(mobile, password, vertifyCode);
            }
        }
    }

    public void showpwd(View view) {
        CheckBox cb = (CheckBox) findViewById(RProxy.registeract_showpwd_chk);
        if (cb.isChecked()) {
            mConfirmPasswordET.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            mPasswordET.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            mConfirmPasswordET.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            mPasswordET.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    public void fetchVertifyCode(View view) {
        if (!ExpUtils.validatePhone(mInputMobileEdtTxt.getText().toString()
                .trim())) {
            mInputMobileEdtTxt
                    .setError(getString(RProxy.loginact_username_edtTxt_not_mobile_error));
            return;
        } else {
            showDialog();
            fetchVertifyCode.fetchVertifyCode(mInputMobileEdtTxt.getText()
                    .toString().trim(), isRegister);
        }
    }

    public void back(View view) {
        finish();
        goLoginAct();
    }

    /**
     * @param
     * @return
     * @throws
     * @Description: 显示等待框
     */
    public void showDialog() {
        progressDialog.show();
    }

    /**
     * @param
     * @return
     * @throws
     * @Description: 隐藏等待框
     */
    public void cancelDialog() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    /**
     * @param @param returnRes
     * @return
     * @throws
     * @Description: 获取验证码成功，跳转下一界面
     */
    public void changeView(String returnRes) {
        // String content = "验证码为:" + returnRes;
        // SMSMMSUtils.saveSMS(RegisterAct.this, Constants.PUBLIC_NUMBER,
        // content,
        // false);
        // Intent intent = new Intent(Intent.ACTION_MAIN);
        // intent.setData(Uri.parse("content://mms-sms/"));
        // NotifyManager.notify(RegisterAct.this, 0, RProxy.app_logo, content,
        // Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "1"), "",
        // content, intent, NotifyManager.FLAG_AUTO_CANCEL);
        Toast.makeText(this, "短信验证码已发出，请耐心等待。。。", Toast.LENGTH_SHORT).show();
        refleshView("");
    }

    /**
     * @param @param returnRes
     * @return
     * @throws
     * @Description: 获取验证码成功，跳转下一界面
     */
    public void changeViewRepeat(String returnRes) {
        Toast.makeText(this, returnRes + "不能重新发送，请耐心等待。。。", Toast.LENGTH_SHORT)
                .show();
        refleshView("");
    }

    /* 显示注册界面，隐藏获取验证码界面 */
    private void refleshView(String vertifycode) {
        registerSclVi.setVisibility(View.VISIBLE);
        fetchVerCodeLL.setVisibility(View.GONE);
        this.mVertifyCodeET.setText(vertifycode);
    }

    /* 找回密码 */
    private void resetPwd(String mobile, String pwd, String vertifycode) {
        forgetPassword.forgetPassword(mobile, pwd, vertifycode);
    }

    /* 注册 */
    private void registerAccount(String mobile, String pwd, String vertifycode) {
        register.register(mobile, pwd, vertifycode);
    }

    /**
     * @param @param jid
     * @return
     * @throws
     * @Description: 注册成功
     */
    public void registerSuccess(String jid) {
        String mobile = mInputMobileEdtTxt.getText().toString().trim();
        PreferencesUtils.setPfValue(RegisterAct.this,
                Constants.ACCOUNT_BAREJID_KEY, jid, String.class.getName());
        PreferencesUtils.setPfValue(RegisterAct.this,
                Constants.ACCOUNT_USER_MOBILE, mobile, String.class.getName());
        PreferencesUtils.setPfValue(RegisterAct.this,
                Constants.ACCOUNT_PASSWORD_KEY, mPasswordET.getText()
                        .toString().trim(), String.class.getName());
        PreferencesUtils.setPfValue(RegisterAct.this,
                Constants.ACCOUNT_VALIDATED, "1", String.class.getName());
        goLoginAct();
    }

    /*
     * <p>Title: onBackPressed</p> <p>Description: </p>
     *
     * @see android.app.Activity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
        finish();
        goLoginAct();
    }

    /* 跳转登陆界面 */
    private void goLoginAct() {
        Intent i = new Intent();
        i.setClass(this, LoginAct.class);
        startActivity(i);
        finish();
    }

    /**
     * Text watcher to test if all fields are field.
     */
    private class NotEmptyTextWatcher implements TextWatcher {

        /**
         * Constructor.
         */
        public NotEmptyTextWatcher() {
        }

        @Override
        public void afterTextChanged(Editable s) {
            boolean enable = !(TextUtils.isEmpty(mInputMobileEdtTxt.getText())
                    || StringUtils.isEmpty(mPasswordET.getText().toString()
                    .trim())
                    || TextUtils.isEmpty(mConfirmPasswordET.getText()) || TextUtils
                    .isEmpty(mVertifyCodeET.getText()));
            findViewById(RProxy.registeract_register_btn).setEnabled(enable);

            boolean vEnable = !TextUtils.isEmpty(mInputMobileEdtTxt.getText());
            findViewById(RProxy.registeract_fetch_vercode_btn).setEnabled(
                    vEnable);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }
    }
}